<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
use think\facade\Cookie;
use think\Validate;
function password($password, $password_code='lshi4AsSUrUOwWV')
{
    return md5(md5($password) . md5($password_code));
}
#获取配置信息
function get_config($name){
	return Db::name('config')->where('name',$name)->value('value');
}
function hSuccess($msg='', $data=[],$count=0,$pages=0,$code=0) {
    return json(['code'=>$code,'data'=>$data,'message'=>$msg,'count'=>$count,'pages'=>$pages]);
}
/**
 * 调用失败
 */
function hError($code=0, $msg='', $data='') {
    return json(['code'=>$code,'message'=>$msg,'data'=>$data]);
}
/**
 * 调用成功
 */
function toSuccess($msg='', $data=[],$count=0,$pages=0,$code=1) {
    return json(['status'=>$code,'data'=>$data,'message'=>$msg,'count'=>$count,'pages'=>$pages]);
}
/**
 * 调用失败
 */
function toError($code=0, $msg='', $data='') {
    return json(['status'=>$code,'message'=>$msg,'data'=>$data]);
}

/**
 * 阿里大鱼短信发送
 * @param [type] $phone     [手机号]
 * @param [type] $code      [验证码]
 */
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
function SendSms($phone)
{
	$code=mt_rand(1000,9999);
    //获取短信配置
    $appkey = get_config('aldy_AppKey');
    $secretkey = get_config('aldy_SecretKey');
    $name = get_config('aldy_name');
    $TemplateCode = get_config('aldy_code');
AlibabaCloud::accessKeyClient($appkey, $secretkey)->regionId('cn-hangzhou')->asDefaultClient();
try {
    $result = AlibabaCloud::rpc()
	  ->product('Dysmsapi')
	  ->version('2017-05-25')
	  ->action('SendSms')
	  ->method('POST')
	  ->host('dysmsapi.aliyuncs.com')
	  ->options([
	                'query' => [
	                  'RegionId' => "cn-hangzhou",
	                  'PhoneNumbers' => $phone,
	                  'SignName' => $name,
	                  'TemplateCode' => $TemplateCode,
	                  'TemplateParam' => "{\"code\":$code}",
	                ],
	            ])
	  ->request();

	if($result['Message']=='OK'){
		Db::name('mobile_code')->insert(['mobile'=>$phone,'code'=>$code,'add_time'=>time()+120]);
		return toSuccess('发送成功,请在120s内完成');
	}else{
		return toError(0,$result['Message']);
	}
} catch (ClientException $e) {
    echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo $e->getErrorMessage() . PHP_EOL;
}
}


/*

 * $name=数据名
 *
 * 具体看https://www.kancloud.cn/manual/thinkphp5_1/354121
 * size=10M
 * */
function file_upload($name,$directory="./uploads",$ro=['size'=>1024*1024*50,'ext'=>'jpg,png,gif,mp4,xlsx,docx,xls,doc,pdf']){
		//上传到本地
		$file = request()->file($name);
	    // 移动到框架应用根目录/uploads/ 目录下
		if(config('is_open_oss')){
			$SaveName = $file->validate($ro)->move($directory,true,true,true,true);
			$fileName=str_replace("./","",$directory).str_replace("\\","/",$SaveName);
			//上传到oss上面
			$oss_data=(new app\common\controller\Oss())->oss_upload($_FILES[$name]["tmp_name"],$fileName);
			return $oss_data;
		}else{
			$info = $file->validate($ro)->move($directory);
			if($info){
		        $SaveName=$info->getSaveName();
		    }else{
		        // 上传失败获取错误信息
		        return ["code"=>404,"msg"=>$file->getError()];
		    }
			$img_url=http_s().$_SERVER['SERVER_NAME']."/".$fileName;
			return ["code"=>200,"img_url"=>$img_url];
		}
}
/*

 * 删除本地文件
 *
 * */
function delFile($path){
        $url=iconv('utf-8','gbk',$path);
        if(strtoupper(substr(PHP_OS,0,3)) != 'WIN'){ //linux
            unlink($path);
        }else{  //Windows
            unlink($url);
        }
}


function http_s(){
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https://')) ? 'https://' : 'http://';
    return $http_type;
}


function get_order($code='D'){

	return $code . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

}


function GetDateTime(){

        $Datetime = date('H');

        $text = 0;

        if($Datetime >= 0 && $Datetime < 7){

            $text = 1;

        }else if($Datetime>=7 && $Datetime<12){

            $text =1;

        }else if($Datetime >= 12 && $Datetime < 14){

            $text = 2;

        }else if($Datetime >= 14 && $Datetime < 18){

            $text = 2;

        }else if($Datetime >= 18 && $Datetime < 22){

            $text = 2;

        }else if($Datetime >= 22 && $Datetime < 24){

            $text = 2;

        }

        return $text;

    }